package com.carp.scaffolding.container;

import com.carp.scaffolding.config.prop.ProjectProperties;
import com.carp.scaffolding.util.CheckUtils;
import com.google.common.collect.Sets;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.Set;

/**
 * @author lile
 * @date 2023/2/22
 */
@Component
@RequiredArgsConstructor
@Getter
public class TemplateContainer {

    private final ProjectProperties projectProperties;
    public static final File TEMPLATE_DIR = new File(System.getProperty("user.dir") + "/src/main/resources/templates");
    private final Set<String> container = Sets.newHashSet();
    private final CheckUtils checkUtils;

    @PostConstruct
    private void init() throws IOException {
        traverseFiles(TEMPLATE_DIR);
    }

    private void traverseFiles(File file) throws IOException {

        if (file.isFile()) {
            if (checkUtils.checkAll(file)) {
                container.add(getRelativePath(file));
            }
            return;
        }

        File[] files = file.listFiles(checkUtils::checkAll);
        Assert.notNull(files, "Files can not be null.");

        if (files.length == 0) {
            File gitKeep = new File(file, ".gitkeep.ftl");
            boolean isSuccessful = gitKeep.createNewFile();
            Assert.isTrue(isSuccessful, "Failed to create new file.");
            container.add(getRelativePath(gitKeep));
            return;
        }

        for (File subFile : files) {
            traverseFiles(subFile);
        }

    }

    private String getRelativePath(File file) {
        return file.getPath().substring(file.getPath().lastIndexOf("templates") + "templates".length());
    }

}
